package cn.fancy.sdk.login.view;

import android.graphics.Color;
import android.text.TextUtils;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import cn.fancy.sdk.pay.WebViewActivity;
import cn.fancy.sdk.utils.SpMmkvUtils;
import com.bytedance.applog.game.GameReportHelper;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.fancy.sdk.QdRegisterCallback;
import cn.fancy.sdk.FancyManager;
import cn.fancy.sdk.baseview.BaseView;
import cn.fancy.sdk.baseview.IActivityManager;
import cn.fancy.sdk.common.utils.LoginSwitchManage;
import cn.fancy.sdk.common.utils.NetworkImpl;
import cn.fancy.sdk.common.utils.ResUtil;
import cn.fancy.sdk.common.utils.SdkAsyncTask;
import cn.fancy.sdk.entity.GuildBaseInfo;
import cn.fancy.sdk.login.QdLoginResult;
import cn.fancy.sdk.login.utils.AccountHelper;
import cn.fancy.sdk.login.utils.AccountHelper.Local_Account;
import cn.fancy.sdk.login.utils.Checker;
import cn.fancy.sdk.login.utils.DBHelper;
import cn.fancy.sdk.login.utils.HttpReq;
import cn.fancy.sdk.utils.TipMessSingle;

/*
 * 快速注册——手机号
 */
public class QuickRegisterView extends BaseView {
    
    IActivityManager activityMgr;
    DBHelper dbHelper;
    private Activity ownerActivity;
    SdkAsyncTask<String> registerAsyncTask = null;
    private Context mContext;
    private long lastTime = 0;
    SdkAsyncTask<String> registerPhoneAsyncTask;
    private EditText mobile_username_input, mobile_password_input, mobile_mess_input;
    private ImageView eyeimg;
    private TextView mSendMess;
    Timer timer;
    Handler handler;
    
    private LinearLayout ll_agreement;
    private CheckBox cb_agreement;
    private TextView link_agreement;
    private TextView tv_agreement;
    private boolean needCheckBox;
    
    public QuickRegisterView(Context context) {
        super(context);
    }
    
    public QuickRegisterView(Activity cActivity, IActivityManager activityMgr) {
        super(cActivity.getBaseContext(), ResUtil.getLayoutId(
            cActivity.getBaseContext(), "guild_quickregister"));
        mContext = cActivity.getBaseContext();
        this.activityMgr = activityMgr;
        ownerActivity = cActivity;
        dbHelper = DBHelper.getInstance(mContext);
        
        initView();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what > 0) {
                    mSendMess.setText(String.format("请%02d秒后重试", msg.what));
                } else {
                    mSendMess.setText("重新获取");
                    mSendMess.setEnabled(true);
                    timer.cancel();
                    
                }
            }
        };
    }
    
    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        this.postInvalidate();
    }
    
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }
    
    private void initView() {
        mSendMess = (TextView) this.findViewById(ResUtil.getId(mContext, "guild_mobile_send_message"));
        mSendMess.setOnClickListener(this);
        mSendMess.setClickable(true);
        
        TextView userRegistBtn = (TextView) this.findViewById(ResUtil.getId(mContext, "guild_normal_regist1"));
        userRegistBtn.setOnClickListener(this);
        
        TextView registsure = (TextView) this.findViewById(ResUtil.getId(mContext, "guild_login_confirm_me"));
        registsure.setOnClickListener(this);
        
        ImageView registcancle = (ImageView) this.findViewById(ResUtil.getId(mContext, "guild_login_cancle_me"));
        registcancle.setOnClickListener(this);
        
        TextView guild_haveaccount = (TextView) this.findViewById(ResUtil.getId(
            mContext, "guild_haveaccount"));
        guild_haveaccount.setOnClickListener(this);
        
        mobile_username_input = (EditText) this.findViewById(ResUtil.getId(
            mContext, "guild_mobile_regist_user"));
        mobile_username_input.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        
        mobile_password_input = (EditText) this.findViewById(ResUtil.getId(
            mContext, "guild_mobile_login_password"));
        mobile_password_input.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        mobile_password_input.addTextChangedListener(new TextWatcher() {
            
            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
                String editable = mobile_password_input.getText().toString();
                String regEx = "[^a-zA-Z0-9]"; // 只能输入字母或数字
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(editable);
                String str = m.replaceAll("").trim(); // 删掉不是字母或数字的字符
                if (!editable.equals(str)) {
                    mobile_password_input.setText(str); // 设置EditText的字符
                    mobile_password_input.setSelection(str.length()); // 因为删除了字符，要重写设置新的光标所在位置
                }
            }
            
            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {
            }
            
            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });
        
        mobile_mess_input = (EditText) this.findViewById(ResUtil.getId(
            mContext, "guild_mobile_regist_mess"));
        mobile_mess_input.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        
        eyeimg = (ImageView) this.findViewById(ResUtil
            .getId(mContext, "eyeimg"));
        eyeimg.setSelected(false);
        eyeimg.setOnClickListener(this);
    
        ll_agreement = (LinearLayout) this.findViewById(ResUtil.getId(mContext, "ll_agreement"));
        cb_agreement = (CheckBox) this.findViewById(ResUtil.getId(mContext, "cb_agreement"));
        link_agreement = (TextView) this.findViewById(ResUtil.getId(mContext, "link_agreement"));
        tv_agreement = (TextView) this.findViewById(ResUtil.getId(mContext, "tv_agreement"));
        needCheckBox = needCheckBoxAgreeMent();
    }
    
    //===================是否展示同意协议
    private static final String DAIMIAO = "daimiao";
    private static final String BA_YOU = "bayou";
    private static final String AGREEMENT_URL = "/mobile/float/game_agreement";
    
    private boolean needCheckBoxAgreeMent() {
        if (GuildBaseInfo.getInstance().getMetaUrl("API_URL").contains(DAIMIAO) || GuildBaseInfo.getInstance().getMetaUrl("API_URL").contains(BA_YOU)) {
            link_agreement.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    //跳h5
                    String url = GuildBaseInfo.getInstance().getMetaUrl("API_URL") + AGREEMENT_URL;
                    WebViewActivity.start(getContext(), url, "游戏服务协议");
                }
            });
            return true;
        } else {
            ll_agreement.setVisibility(INVISIBLE);
            return false;
        }
    }
    
    private boolean verifyCheckBox(){
        if(needCheckBox && !cb_agreement.isChecked()){
            Toast.makeText(getContext(), "请先确认已阅读《游戏服务协议》", Toast.LENGTH_LONG).show();
            tv_agreement.setTextColor(Color.parseColor("#FF0000"));
            return false;
        }
        return true;
    }
    //===================是否展示同意协议end
    
    @Override
    public void onClick(View v) {
        long nowTime = System.currentTimeMillis();
        if (nowTime - lastTime < 1500) {
            lastTime = nowTime;
            return;
        }
        
        int vid = v.getId();
        if (vid == ResUtil.getId(mContext, "guild_normal_regist1")) {
            activityMgr.popViewFromStack();
            activityMgr.pushViewToStack(new RegisterAccountNoPhoneView(ownerActivity, activityMgr));
        } else if (vid == ResUtil.getId(mContext, "guild_login_confirm_me")) {
            if(!verifyCheckBox()){
                return;
            }
            submitRequest();
        } else if (vid == ResUtil.getId(mContext, "guild_login_cancle_me")) {
            activityMgr.popViewFromStack();
            activityMgr.pushViewToStack(new LoginView(ownerActivity, activityMgr));
        } else if (vid == ResUtil.getId(mContext, "guild_mobile_send_message")) {
            sendPhoneVerify();
        } else if (vid == ResUtil.getId(mContext, "guild_haveaccount")) {
            activityMgr.popViewFromStack();
            activityMgr.pushViewToStack(new LoginView(ownerActivity, activityMgr));
        } else if (vid == ResUtil.getId(mContext, "eyeimg")) {
            if (eyeimg.isSelected()) {
                eyeimg.setSelected(false);
                
                // eyeImg.setText("显示");
                eyeimg.setBackgroundResource(ResUtil.getDrawableId(mContext, "guild_eye_off"));
                mobile_password_input.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            } else {
                eyeimg.setSelected(true);
                // eyeImg.setText("隐藏");
                eyeimg.setBackgroundResource(ResUtil.getDrawableId(mContext, "guild_eye_on"));
                mobile_password_input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            }
        }
    }
    
    @Override
    public void stopSyncTask(boolean stop) {
        if (registerAsyncTask != null) {
            registerAsyncTask.cancel(stop);
        }
    }
    
    private void sendPhoneVerify() {
        final String uphone = mobile_username_input.getText().toString().trim();
        
        String mobile_format = Checker.checkPhoneNumber(uphone, mContext);
        if (!mobile_format.equals(Checker.IS_OK)) {
            Toast.makeText(mContext, TipMessSingle.five_mobilenil,
                Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (!NetworkImpl.isNetworkConnected(getContext())) {
            Toast.makeText(getContext(), TipMessSingle.ten_networkerr,
                Toast.LENGTH_LONG).show();
            return;
        }
        
        final Map<String, String> regMap = GuildBaseInfo.getInstance().getRegisterSmsCodeParamsGuide(getContext(), uphone, "send_phone_verify");
        registerPhoneAsyncTask = new SdkAsyncTask<String>() {
            
            @Override
            protected String doInBackground() {
                Log.e("guidebindphone:", "guidebindphone:" + regMap.toString());
                return HttpReq.doGuildRequest(regMap);
            }
            
            @Override
            protected void onPostExecute(String rst) {
                Log.e("guidebindphone:", "guidebindphone:" + rst);
                if (rst == null) {
                    rst = "";
                }
                if ("".equals(rst)) {
                    Toast.makeText(mContext, TipMessSingle.ten_networkerr,
                        Toast.LENGTH_LONG).show();
                    return;
                }
                try {
                    JSONObject json = new JSONObject(rst);
                    String state = json.getString("state");
                    JSONObject jsonState = new JSONObject(state);
                    int code = jsonState.getInt("code");
                    String msgmsg = jsonState.optString("msg");
                    if (code != 1) {
                        Toast.makeText(getContext(), msgmsg, Toast.LENGTH_LONG)
                            .show();
                        return;
                    }
                    String msg = json.getString("data");
                    JSONObject msgjson = new JSONObject(msg);
                    String smsCode = String.valueOf(msgjson.optInt("code"));
                    String phone = String.valueOf(msgjson.optInt("phone"));
                    
                    Log.e("smsCode", "smsCode" + smsCode);
                    Log.e("phone", "phone" + phone);
                    Toast.makeText(mContext, "获取成功，验证码有效时间为1小时",
                        Toast.LENGTH_LONG).show();
                    mSendMess.setEnabled(false);
                    timer = new Timer();
                    TimerTask timerTask = new TimerTask() {
                        int i = 55;
                        
                        @Override
                        public void run() {
                            Message msg = new Message();
                            msg.what = i--;
                            handler.sendMessage(msg);
                        }
                    };
                    timer.schedule(timerTask, 0, 1000);
                } catch (JSONException e) {
                    Log.d("BindPhone", "registed phone returns error msg");
                    e.printStackTrace();
                }
            }
            
            @Override
            public Activity getOwnerActivity() {
                return ownerActivity;
            }
            
            @Override
            protected void onCancelled() {
            }
            
        };
        
        registerPhoneAsyncTask.execute();
    }
    
    public void submitRequest() {
        final String password = mobile_password_input.getText().toString().trim();
        final String uphone = mobile_username_input.getText().toString().trim();
        final String mess = mobile_mess_input.getText().toString().trim();
        String mobile_format = Checker.checkPhoneNumber(uphone, mContext);
        if (!mobile_format.equals(Checker.IS_OK)) {
            Toast.makeText(mContext, TipMessSingle.five_mobilenil,
                Toast.LENGTH_SHORT).show();
            return;
        }
        if (!NetworkImpl.isNetworkConnected(getContext())) {
            Toast.makeText(getContext(), TipMessSingle.ten_networkerr,
                Toast.LENGTH_LONG).show();
            return;
        }
        if (mess.equals("")) {
            Toast.makeText(mContext, TipMessSingle.five_codenil,
                Toast.LENGTH_SHORT).show();
            return;
        }
        String password_format = Checker.checkPassword(password, mContext);
        if (!password_format.equals(Checker.IS_OK)) {
            Toast.makeText(getContext(), TipMessSingle.five_passnil,
                Toast.LENGTH_LONG).show();
        }
        final Map<String, String> regMap = GuildBaseInfo.getInstance().phoneRegisterParams(
            getContext(), uphone, password, mess, "register");
        if (regMap == null) {
            Toast.makeText(mContext, "传入参数有误...", Toast.LENGTH_SHORT).show();
            return;
        }
        
        registerPhoneAsyncTask = new SdkAsyncTask<String>() {
            
            @Override
            protected String doInBackground() {
                Log.e("guidebindphone:", "guidebindphone:" + regMap);
                return HttpReq.doGuildRequest(regMap);
            }
            
            @Override
            protected void onPostExecute(String rst) {
                Log.e("guidebindphonerst:", "guidebindphonerst:" + rst);
                
                if (TextUtils.isEmpty(rst)) {
                    Toast.makeText(mContext, TipMessSingle.ten_networkerr, Toast.LENGTH_LONG).show();
                    return;
                }
                try {
                    JSONObject json = new JSONObject(rst);
                    String state = json.getString("state");
                    JSONObject jsonState = new JSONObject(state);
                    
                    int code = jsonState.getInt("code");
                    String msgmsg = jsonState.optString("msg");
                    if (code != 1) {
                        Toast.makeText(getContext(), msgmsg, Toast.LENGTH_LONG).show();
                        return;
                    }
                    String msg = json.getString("data");
                    JSONObject msgjson = new JSONObject(msg);
                    
                    String user_id = msgjson.optString("id");
                    String token = msgjson.optString("ticket");
                    int time = msgjson.optInt("expires_in");
    
                    if (TextUtils.isEmpty(msgjson.optString("float_window_url"))) {
                        String httpsFloatUrl = msgjson.getString("float_window_url");
                        SpMmkvUtils.putValue(getOwnerActivity(), SpMmkvUtils.KEY_HTTPS_FLOAT_URL, httpsFloatUrl);
                    }
    
                    if (!TextUtils.isEmpty(msgjson.optString("game_discount"))) {
                        String discount = msgjson.getString("game_discount");
                        SpMmkvUtils.putValue(getOwnerActivity(), SpMmkvUtils.KEY_DISCOUNT, discount);
                    }else {
                        SpMmkvUtils.putValue(getOwnerActivity(), SpMmkvUtils.KEY_DISCOUNT, "0");
                    }
                    
                    // 进行状态判断
                    DBHelper.SDK_ACCOUNT s_acct = new DBHelper.SDK_ACCOUNT();
                    s_acct.auto_login = 1;
                    s_acct.user_name = uphone;
                    s_acct.user_password = password;
                    s_acct.is_valid = AccountHelper.ACCOUNT_VALID;
                    s_acct.user_id = user_id;
                    
                    Local_Account local_acct = new Local_Account();
                    local_acct.username = uphone;
                    local_acct.password = password;
                    local_acct.isValid = AccountHelper.ACCOUNT_VALID;
                    AccountHelper.updateLocalAccounts(local_acct);
                    
                    if (dbHelper.isAccountPresent(s_acct)) {
                        dbHelper.updateAccount(s_acct);
                    } else {
                        dbHelper.insertNewAccount(s_acct);
                    }
                    
                    QdLoginResult loginResult = new QdLoginResult(user_id, uphone, token, String.valueOf(time), "0", "1");
                    GuildBaseInfo.getInstance().SetLoginAuMess(uphone, password, String.valueOf(LoginSwitchManage.getInstance().result_authenticate));
                    GuildBaseInfo.getInstance().setAccountInfo(uphone, password, user_id);
                    GuildBaseInfo.setAcctsInfo(uphone, user_id, password);
    
                    if (FancyManager.getInstance().isAdvertIdBool()) {
                        GameReportHelper.onEventRegister("quick", true);
                    }
    
                    int authenticateInt = Integer.parseInt(msgjson.optString("pop_reg_idcard"));
                    switch (authenticateInt){
                        case 0:
                            activityMgr.notifyLoginSuccess(loginResult);
                            activityMgr.finishDialogOrActivity();
                            break;
                        case 1:
                            activityMgr.pushViewToStack(new RealViewMust(ownerActivity, activityMgr, true));
                            break;
                        case 2:
                            activityMgr.pushViewToStack(new RealViewMust(ownerActivity, activityMgr, false));
                            break;
                    }
                    
                    FancyManager.getInstance().CallRegister(QdRegisterCallback.SUCCEEDED, QdRegisterCallback.BY_PHONE);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            
            @Override
            public Activity getOwnerActivity() {
                return ownerActivity;
            }
            
            @Override
            protected void onCancelled() {}
            
        };
        
        registerPhoneAsyncTask.execute();
    }
    
}
